var JcropOption = {
    actual:false,
    activate:true,
    ratio:1,
    croper:'home.croper.php'
}

var imagesInOrder = false;

$(document).ready(function () {
    $('#sortableImages').disableSelection().sortable();
    $('#selectCategoria').addClass('span12');
    $('#formHome').submit(function () {
        if (!imagesInOrder) {
            ordenarImagenes();
            $('#loaderModal').modal('show')
            return false
        } else {
            return true;
        }
    });
    fileuploaderInit();
    onfileuploaddone();
    dropzone();
})

$(window).load(function () {
    $('.preview > img').imagesFrame(120, 68, true)
})

function onfileuploaddone () {
    $('.borrarImagen').unbind('click').click(borrarImagen)
    $('.borrarError').click(borrarError)
}

function fileuploaderInit () {
    $('#formHome').fileupload({
        url: BASE_URL+'admin/php/uploaders/home.uploader.php',
        autoUpload:true
    })
    .bind('fileuploaddone', function (e, data) {
        $('#hiddenData').append('<input type="hidden" name="newImages[]" id="'+data.result.files[0].nombre+'" value="5" />')
        setTimeout(
            function () {
                $('.preview > img.recortable').imagesFrame(120, 68, true)
                onfileuploaddone();
            }, 
            300
        )
    })
    .bind('fileuploadfail', function (e, data){
        setTimeout(
            function () {
                $('.preview > img.recortable').imagesFrame(120, 68, true)
                onfileuploaddone();
            }, 
            300
        )
    })
}

function ordenarImagenes () {
    var data = '', id;
    $('#sortableImages li').each(function (i) {
        if (id = $(this).data('id')) {
            data += '&orden[]='+i;
            data += '&id[]='+id;
        } else {
            $('#hiddenData #'+$(this).data('nombre')).val($(this).data('nombre')+','+i+','+$(this).data('extension'))
        }
    })
    $.ajax({
        type:'POST',
        url:BASE_URL+'admin/php/controllers/ordenar.controller.php',
        data: 'tabla=imagen'+data,
        success:function () {
            imagesInOrder = true;
            $('#formHome').submit();
        }
    })    
}

function borrarImagen () {
    var data = {
        src:$(this).data('src'),
        carpeta:$(this).data('carpeta'),
        id:($(this).data('id'))?$(this).data('id'):0
    }
    $('#'+$(this).data('src').replace(/\.(jpg|png|gif)$/, '')).remove();
    $.ajax({
        type:'POST',
        url:BASE_URL+'admin/php/controllers/borrarImagenes.controller.php',
        data: data
    })
    $(this).parents('li').remove();
}

function borrarError () {
    $(this).parents('li').remove();
}